<?php
namespace api\modules\v1\models\userFund;

use api\modules\v1\models\Common;
use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\pay\Alipay;
use common\models\Status;
use common\models\user\UserUnusualLog;
use common\models\userFund\RechargeSetting;
use common\models\userFund\UserRechargeOrder;
use yii\base\Exception;
use Yii;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class RechargeOrder extends UserRechargeOrder
{

    //充值规则
    public function getConfig() {
        try{
            $user = Yii::$app->getUser()->getIdentity()->toArray();

            $settingMoney = [];
            $settingList = RechargeSetting::getByWhere(['status' => Status::COMMON_RADIO_YES],'*','id ASC');
            foreach ($settingList as $key => $value) {
                $settingMoney[] = [
                    'id' => (int) $value['id'],
                    'name' => $value['name'],
                    'money' => sprintf("%.2f",$value['money']),
                    'ios_id' => $value['ios_id'] ?: '',
                ];
            }
            $data['setting_money'] = $settingMoney;
            $data['user_money'] = $user['money'];

            $config = static::getCommonByKey(['recharge_start','recharge_end','recharge_switch']);

            $configArr = [
                "当前充值开关".($config['recharge_switch'] == Status::COMMON_RADIO_YES ? '正常开启' : '已经关闭'),
                "充值时间为{$config['recharge_start']} - {$config['recharge_end']}",
                "充值成功后，资金将在30分钟内到账。",
            ];
            $data['config'] = $configArr;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 创建订单
     * @return array
     */
    public function createOrder() {
        $trans = Yii::$app->db->beginTransaction();
        try {

            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            CacheKeys::checkFrequency($userInfo['id'],1);

            # 零钱封禁
            UserUnusualLog::checkUserUnusual($userInfo['id'],Status::USER_UNUSUAL_TYPE_MONEY);
            // 检查用户信息
            (new \common\models\user\User()) -> checkInfo($userInfo);

            $payPassword = Yii::$app->request->post('pay_password','');
            $money = Yii::$app->request->post('money',0);
            $payWay = Yii::$app->request->post('pay_way',0); //2-银行卡 3-支付宝
            $receiptData = Yii::$app->request->post('receipt_data',""); //ios返回的数据

            if (!is_numeric($money) || $money < 0) {
                throw new Exception('充值金额不合法');
            }

            // 校验充值规则
            $this->checkRechargeConfig($money);

            if (empty($payWay)) {
                throw new Exception('请选择付款方式');
            }

            if (!in_array($payWay,array_keys(Status::PAY_WAY_MAP))) {
                throw new Exception('付款方式不合法');
            }
            if ((!Yii::$app->security->validatePassword($payPassword, $userInfo['pay_password']))) {
                throw new Exception("交易密码不正确");
            }

            // 检查设备码
            Common::checkDeviceCode($userInfo);

            $orderNumber = $this->_createOrderNumber();
            $order['order_number'] = $orderNumber;
            $order['user_id'] = $userInfo['id'];
            $order['money'] = round($money, 2);
            $order['status'] = Status::RECHARGE_STATUS_DOING;
            $order['create_time'] = date("Y-m-d H:i:s");
            $order['pay_way'] = $payWay;
            $res = static::insertData($order);
            if ($res === false) {
                throw new Exception('系统异常');
            }

            if ($payWay) {
                // 银行卡支付
                if ($payWay == Status::PAY_WAY_BANK) {
                    throw new Exception('暂未开通该支付方式，敬请期待');
                }

                //支付宝支付
                if ($payWay == Status::PAY_WAY_ALIPAY) {
                    $aliPayModel = new Alipay();

                    $resAlipay = $aliPayModel->payRecharge($orderNumber, 'app');

                    if (isset($resAlipay['status']) && $resAlipay['status'] === false) {
                        throw new Exception($res['message']);
                    }
                    $trans->commit();
                    return Functions::formatRestAPI(0, '创建成功，请尽快支付', $resAlipay);
                }

                //苹果内购
                if ($payWay == Status::PAY_WAY_IOS) {
                    if (empty($receiptData)) {
                        throw new Exception("苹果支付参数有误！");
                    }
                    $this->iosPay($orderNumber, $receiptData);
                    $trans->commit();
                    return Functions::formatRestAPI(0, '创建成功，请尽快支付');
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '订单创建成功,请尽快完成付款');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        }
    }


    //记录
    public function getList($page = 1, $size = 20)
    {
        try{
            $page = (int)$page;
            $size = (int)$size;
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            $where['user_id'] = $userInfo['id'];

            $count = static::getCountByWhere($where);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByWhere($where, ['*'], 'id DESC', $offset, $size)->asArray()->all();
            $result = [];
            foreach ($list as $v) {
                $result[] = [
                    'id' => (int) $v['id'],
                    'user_id' => $v['user_id'],
                    'order_number' => $v['order_number'],
                    'money' => $v['money'],
                    'create_time' => $v['create_time'] ?: '',
//                    'success_time' => $v['success_time'] ?: '',
//                    'defeat_reason' => $v['defeat_reason'] ?: '',
//                    'defeat_time' => $v['defeat_time'] ?: '',
                    'status' => $v['status'],
                    'status_name' => STATUS::RECHARGE_STATUS_MAP[$v['status']],
                ];
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }


}
